--
-- Author: mm
-- Date: 2018-03-24 15:51:35
--
-- NewguildCreateView
-- 创建工会UI

local NewguildIconRender = import(".renders.NewguildIconRender")
local ScrollCircleView = require("app.widget.ScrollCircleView")
local NewguildSetIconRender = import(".renders.NewguildSetIconRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.NewCreateGuildUI

local MAX_WORD_LEN = tonumber( GD:getSystemPar( "guildNameLength", 12 ) ) -- 公会名字最长字符数

local baseIconNum = 7 -- 基础图案个数
local baseIconMidIdx = 4 -- 基础图案中点索引

local baseIconColorNum = 15 -- 基础图案色值个数
local ErrorMsg_OutOfMax = string.format(L("lua_code_text_315"), Constant.NICKNAME_MAX_LEN)
local ErrorMsg_NotEnoughLen = string.format(L("lua_code_text_76"), Constant.NICKNAME_MIN_LEN)
local ErrorMsg_NotValid = L("lua_code_text_337")
-- data = { NewguildModel:getBaseIconColorList(), NewguildModel:getAdditionalIconColorList() }
function ClassRef:init()
	local isRename = self._data[3]

	self._ui.Button_quxiao:addClickEventListener(function() -- 上一步按钮？
		executeFunc(self._onCloseView)
	end)
	self._ui.Button_back:addClickEventListener(function() -- X按钮
		executeFunc(self._onCloseView)
	end)

	self._ui.Button_queding:addClickEventListener(function()
		local guildNameTemp = self._editText:getText()

		local ok, msg = self:_checkNameValid(guildNameTemp)
		if ok then

			if isRename then
				--如果是改名界面 弹出二次确认框
				local contentStr = string.format(L("rename3"),L("itemname_75100101"),guildNameTemp)

				local confirmDialog = display.newConfirmDialog(contentStr,
					function()
						executeFunc(self._onOperate, "renameGuild", self:getPreCreateInfo())
						self:closeView()
					end,nil)
				confirmDialog:setConfirmText(L("tips_ok"))
				confirmDialog:setCancelText(L("tips_cancel"))
				confirmDialog:replaceTextByRichText(self:getRichText(guildNameTemp,"#344696"))
				UIHandler:addPopDialog(confirmDialog, 1, true)

			else
				executeFunc(self._onOperate, "create_guild")
			end
		else
			display.pushToast(msg)
		end
	end)

	if isRename then
		--如果是改名界面 则将两个按钮改为相应的取消和确定文本
		self._ui.Button_quxiao:findChild("name"):setString(L("tips_cancel"))
		self._ui.Button_queding:findChild("name"):setString(L("tips_ok"))

		self._ui.Panel_tlt:findChild("tlt"):setString(L("rename5"))
	end

	self._guildIcon = NewguildIconRender.create( self._ui.Panel_left:getChildByName( "icon" ) )
	self:_initGuildName()

	if self._ui.Panel_coin then
		self._ui.Panel_coin:setVisible(false)
	end

	--[[
	self._ui.Panel_coin:getChildByName( "num" ):setString( UD:getGold() )
    self._ui.Panel_coin:addTouchEventListener(function(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            local param = {itemId = 99,tipsType = Enums.TipsType.daibi}
            local boundingBoxTemp = sender:getBoundingBox()
            local worldPosTemp = sender:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
            boundingBoxTemp.x = worldPosTemp.x
            boundingBoxTemp.y = worldPosTemp.y
            param.boundingBox = boundingBoxTemp
            app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params = param})
        end
    end)
    --]]

	local baseIconConf = GD:queryGuildCreateById( "flagIconBig" )
	self._baseIconList = string.split( baseIconConf.strPar, ";" )
	self._baseIconCurIdx = baseIconMidIdx -- 基础图标当前指向索引位
	----------------scrollcircle -------------------
	--设置一个模板遮罩
	local panelIcon = self._ui["Panel_top/Panel_icon"]
	local params = {
		parentNode = panelIcon,
		size = panelIcon:getContentSize(),
		subNodeClass = NewguildSetIconRender,
		paddingLen = -50,
		subNodeScales = {min = 0.65, max = 1},
		selectedMode = 1,
		selectedCb = handler(self,self.changeSelectedBaseIcon)
	}

	local scrollData = {}
	for k,v in ipairs(self._baseIconList) do
		scrollData[k] = {}
		scrollData[k].id = tonumber(k)
		scrollData[k].baseIconId = v
	end

	self._scrollCircleBase = ScrollCircleView.new( params )
	self._scrollCircleBase:setData(scrollData,baseIconMidIdx)
	---------------------------------------------------

	-- 公会基础图标选择部分
	self._ui.Panel_top:findChild( "Panel_icon/Button_l" ):addClickEventListener(function()
		self._scrollCircleBase:goPreSelect(true)
	end)
	self._ui.Panel_top:findChild( "Panel_icon/Button_r" ):addClickEventListener(function()
		self._scrollCircleBase:goNextSelect(true)
	end)

	-- 初始化基础图案颜色节点
	--local index = 0
	self._baseIconColorList = {}
	local topPanelColor = self._ui.Panel_top:getChildByName( "Panel_color" )
	-- 以下：异步初始化基础颜色节点
	-- local function delayInitBaseColor()
	-- 	index = index + 1
	-- 	if index <= baseIconColorNum then
	-- 		local baseColorRender = self:_initBaseColorNode()
	-- 		local panelTemp = baseColorRender:getChildByName( "Panel" )
	-- 		panelTemp:setTag( index )
	-- 		panelTemp:getChildByName( "bg" ):setColor( self._data[1][index] )
	-- 		display.uiAddClick(panelTemp, function()
	-- 			self:_selectedBaseColor( panelTemp:getTag() )
	-- 		end)
	-- 		topPanelColor:getChildByName( "Node_" .. index ):addChild( baseColorRender )
	-- 		self._baseIconColorList[ index ] = baseColorRender
	-- 	else
	-- 		topPanelColor:stopAction(self._baseColorAction)
	-- 		self._baseColorAction = nil

	-- 		self:_selectedBaseColor( ( baseIconColorNum + 1 ) / 2 ) -- 默认选中 ( baseIconColorNum + 1 ) / 2 颜色
	-- 	end
	-- end
	-- self._baseColorAction = topPanelColor:schedule(delayInitBaseColor, 0)

	-- 以下：同步初始化基础颜色节点
	for i = 1, baseIconColorNum do
		local baseColorRender = self:_initBaseColorNode()
		local panelTemp = baseColorRender:getChildByName( "Panel" )
		panelTemp:setTag( i )
		panelTemp:getChildByName( "bg" ):setColor( self._data[1][i] )
		display.uiAddClick(panelTemp, function()
			self:_selectedBaseColor( panelTemp:getTag() )
		end)
		topPanelColor:getChildByName( "Node_" .. i ):addChild( baseColorRender )
		self._baseIconColorList[ i ] = baseColorRender
	end
	self:_selectedBaseColor( ( baseIconColorNum + 1 ) / 2 ) -- 默认选中 ( baseIconColorNum + 1 ) / 2 颜色



	local additionalIconConf = GD:queryGuildCreateById( "flagIconLittle" )
	self._additionalIconList = string.split( additionalIconConf.strPar, ";" )
	self._additionalIconCurIdx = baseIconMidIdx -- 基础图标当前指向索引位


	----------------scrollcircle -------------------
	--设置一个模板遮罩
	local panelIconAddition = self._ui["Panel_bom/Panel_icon"]
	local paramsAddition = {
		parentNode = panelIconAddition,
		size = panelIconAddition:getContentSize(),
		subNodeClass = NewguildSetIconRender,
		paddingLen = -50,
		subNodeScales = {min = 0.65, max = 1},
		selectedMode = 1,
		selectedCb = handler(self,self.changeSelectedAdditionIcon)
	}

	local scrollDataAddition = {}
	for k,v in ipairs(self._additionalIconList) do
		scrollDataAddition[k] = {}
		scrollDataAddition[k].id = tonumber(k)
		scrollDataAddition[k].additionIconId = v
	end

	self._scrollCircleAddition = ScrollCircleView.new( paramsAddition )
	self._scrollCircleAddition:setData(scrollDataAddition,baseIconMidIdx)
	---------------------------------------------------

	-- 公会附加图标选择部分
	self._ui.Panel_bom:findChild( "Panel_icon/Button_l" ):addClickEventListener(function()
		self._scrollCircleAddition:goPreSelect(true)
	end)
	self._ui.Panel_bom:findChild( "Panel_icon/Button_r" ):addClickEventListener(function()
		self._scrollCircleAddition:goNextSelect(true)
	end)

	-- 初始化附加图案颜色节点
	--local index = 0
	self._additionalIconColorList = {}
	local bomPanelColor = self._ui.Panel_bom:getChildByName( "Panel_color" )
	-- 以下：异步初始化附加颜色节点
	-- local function delayInitAdditionalColor()
	-- 	index = index + 1
	-- 	if index <= baseIconColorNum then
	-- 		local additionalColorRender = self:_initBaseColorNode()
	-- 		local panelTemp = additionalColorRender:getChildByName( "Panel" )
	-- 		panelTemp:setTag( index )
	-- 		panelTemp:getChildByName( "bg" ):setColor( self._data[2][index] )
	-- 		display.uiAddClick(panelTemp, function()
	-- 			self:_selectedAdditionalColor( panelTemp:getTag() )
	-- 		end)
	-- 		bomPanelColor:getChildByName( "Node_" .. index ):addChild( additionalColorRender )
	-- 		self._additionalIconColorList[ index ] = additionalColorRender
	-- 	else
	-- 		bomPanelColor:stopAction(self._additionalColorAction)
	-- 		self._additionalColorAction = nil

	-- 		self:_selectedAdditionalColor( ( baseIconColorNum + 1 ) / 2 ) -- 默认选中 ( baseIconColorNum + 1 ) / 2 颜色
	-- 	end
	-- end
	-- self._additionalColorAction = bomPanelColor:schedule(delayInitAdditionalColor, 0)

	-- 以下：同步初始化附加颜色节点
	for i = 1, baseIconColorNum do
		local additionalColorRender = self:_initBaseColorNode()
		local panelTemp = additionalColorRender:getChildByName( "Panel" )
		panelTemp:setTag( i )
		panelTemp:getChildByName( "bg" ):setColor( self._data[2][i] )
		display.uiAddClick(panelTemp, function()
			self:_selectedAdditionalColor( panelTemp:getTag() )
		end)
		bomPanelColor:getChildByName( "Node_" .. i ):addChild( additionalColorRender )
		self._additionalIconColorList[ i ] = additionalColorRender
	end
	self:_selectedAdditionalColor( ( baseIconColorNum + 1 ) / 2 ) -- 默认选中 ( baseIconColorNum + 1 ) / 2 颜色


end

function ClassRef:_checkNameValid(str)
	local errorMsg = nil

	local len = string.counting(str)

	if len > Constant.NICKNAME_MAX_LEN then
		errorMsg = ErrorMsg_OutOfMax
		return false,errorMsg
	end

	if len < Constant.NICKNAME_MIN_LEN then
		errorMsg = ErrorMsg_NotEnoughLen
		return false,errorMsg
	end

	local mathch = string.filter_spec_chars(str)

	if str~=mathch then
		errorMsg = ErrorMsg_NotValid
		return false,errorMsg
	end

	return true
end


function ClassRef:getRichText(name,colorStr)
	local defaults = {
		KEY_FONT_FACE = Res.font,
		KEY_FONT_SIZE = app:isLanguageEN() and 18 or 22,
		KEY_FONT_COLOR_STRING = "#2F0C04",
	}
	local str1 = display.getRichTextFontXml(name,colorStr,22)
	local str = string.format(L("rename3"),L("itemname_75100101"),str1)

	local richText = ccui.RichText:createWithXML( str, defaults )
	return richText
end

-- 返回操作之后的数据
function ClassRef:getPreCreateInfo()
	local params = {
		name = self._editText:getText(),
		flagBaseIcon = self._baseIconList[self._baseIconCurIdx],
		flagAdditionalIcon = self._additionalIconList[self._additionalIconCurIdx],
		flagBaseIconColor = self._baseIconColorCurIdx,
		flagAdditionalIconColor = self._additionalIconColorCurIdx
	}
	return params
end

-- 工会名字输入框 处理
function ClassRef:_initGuildName()
	local function onEditCallback(strEventName,sender)
		local edit = sender
		if strEventName == "changed" then
			local text = edit:getText()
			--local ulen = string.ulen(text)
			local ulen = string.counting(text)
			if ulen > MAX_WORD_LEN then
				local newStr = string.usubstr(text,MAX_WORD_LEN)
				if text~=newStr then
					edit:setText(newStr)
					text = newStr
					display.pushToast(string.format(L("max_input_char"), MAX_WORD_LEN))
				end
			end
		end
	end
	self._editText = display.replaceTextFieldWithEditBox( self._ui.Panel_left:getChildByName( "TextField" ) )
	self._editText:registerScriptEditBoxHandler(onEditCallback)
	self._editText:setReturnType(cc.KEYBOARD_RETURNTYPE_DONE)
	self._editText:setTextHorizontalAlignment(cc.TEXT_ALIGNMENT_CENTER)
end

-- 处理基础图标颜色node
function ClassRef:_initBaseColorNode()
	local renderTemp = cc.CSLoader:createNode( Res.NewGuildFlagColorNode )
	-- 设置选中状态
	renderTemp.setSelected = function( _, selecetd )
		renderTemp:findChild( "Panel/selected" ):setVisible( selecetd )
	end
	renderTemp:setSelected( false )
	return renderTemp
end

function ClassRef:_selectedBaseColor( baseColorNodeIdx )
	-- print( " ---------------------->>>> 基础图案个数:" , #self._baseIconColorList, baseColorNodeIdx )
	for i = 1, baseIconColorNum do
		self._baseIconColorList[ i ]:setSelected( false )
	end
	self._baseIconColorList[ baseColorNodeIdx ]:setSelected( true )
	self._baseIconColorCurIdx = baseColorNodeIdx

	self._guildIcon:setBaseIconColor( self._data[1][baseColorNodeIdx] )

	local data = self._scrollCircleBase:getData()
	if data then
		for k,v in ipairs(data) do
			v.baseIconColor = self._data[1][baseColorNodeIdx]
		end
		self._scrollCircleBase:refreshData(data)
	end
end

function ClassRef:_selectedAdditionalColor( additionalColorNodeIdx )
	-- print( " ---------------------->>>> 附加图案个数:" , #self._additionalIconColorList, additionalColorNodeIdx )
	for i = 1, baseIconColorNum do
		self._additionalIconColorList[ i ]:setSelected( false )
	end
	self._additionalIconColorList[ additionalColorNodeIdx ]:setSelected( true )
	self._additionalIconColorCurIdx = additionalColorNodeIdx

	self._guildIcon:setAdditionalIconColor( self._data[2][additionalColorNodeIdx] )

	local data = self._scrollCircleAddition:getData()
	if data then
		for k,v in ipairs(data) do
			v.additionIconColor = self._data[2][additionalColorNodeIdx]
		end
		self._scrollCircleAddition:refreshData(data)
	end
end

--选中的回调
function ClassRef:changeSelectedBaseIcon(data)
	--dump(data)
	self._baseIconCurIdx = data.id
	self._guildIcon:setBaseIcon( data.baseIconId )
	local nodes = self._scrollCircleBase:getAllNodes()
	for k,v in ipairs(nodes) do
		v:setSelected(v:getData().id == data.id)
	end
end

--额外的图标选中回调
function ClassRef:changeSelectedAdditionIcon(data)
	self._additionalIconCurIdx = data.id
	self._guildIcon:setAdditionalIcon( data.additionIconId )
	local nodes = self._scrollCircleAddition:getAllNodes()
	for k,v in ipairs(nodes) do
		v:setSelected(v:getData().id == data.id)
	end
end

return ClassRef
